package com.jasonchoi.security.commons.security.authentication;

import com.jasonchoi.security.commons.base.BaseRestResult;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: JasonChoi
 * @Date: 2020/1/8 10:16
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException ex) throws IOException, ServletException {
        String message = null;
        if (ex instanceof UsernameNotFoundException || ex instanceof BadCredentialsException) {
            message = "用户名或密码错误";
        } else if (ex instanceof DisabledException) {
            message = "账户被禁用";
        } else {
            message = "登录失败!";
        }
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpServletResponse.getWriter().write(BaseRestResult.error(message).toJson());
    }
}
